<?php

namespace app\controller;

use app\BaseController;

class Index extends BaseController
{
    public const AppServerList = [
        //beta应用 xshpppy-app-demo
        'xshoppy-app-demo.cn.utools.club' => [                                  //网关地址域名
            'app_name' => "xshoppy-app-demo",                                   //应用名称
            'client_id' => "286cba7025aef6c06a185de64c7abbd2",                  //API key
            'client_secret' => "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",         //API secret Key
            'redirect_uri' => "https://xshoppy-app-demo.cn.utools.club/code",   //扩展URL
            'nonce' => "xxxxx"
        ],
        //beta应用 xshpppy-app-demo2
        'xshoppy-app-demo2.cn.utools.club' => [
            'app_name' => "xshoppy-app-demo2",
            'client_id' => "Px5C0zxy2WCq3vSqjVjcqy2ZRL2xqmiR",
            'client_secret' => "shop_HltZ2sGST1WEYea6nqFjyHrZdx5bbcJI",
            'redirect_uri' => "https://xshoppy-app-demo2.cn.utools.club/code",
            'nonce' => "xxxxx"
        ],
        //beta应用 xshpppy-app-demo2
        'xshoppy-app-demo2.cn.utools.club' => [
            'app_name' => "xshoppy-app-demo2",
            'client_id' => "Px5C0zxy2WCq3vSqjVjcqy2ZRL2xqmiR",
            'client_secret' => "shop_HltZ2sGST1WEYea6nqFjyHrZdx5bbcJI",
            'redirect_uri' => "https://xshoppy-app-demo2.cn.utools.club/code",
            'nonce' => "xxxxx"
        ],
    ];


    //权限
    public const scope = "write_script_tags,write_script_tags,write_script_tags,write_script_tags";
    public const GET_TOKEN_URL = "/admin/oauth/access_token";

    //应用市场跳转的地址
    public function install()
    {
        $shop = $this->request->get('shop');

        if(strpos($shop,'http') != true){
            $shop = 'https://'.$shop;
        }

        $redirect_uri = sprintf('%s/admin/oauth/authorize?client_id=%s&scope=%s&redirect_uri=%s&state=%s&response_type=code',
            $shop,
            self::AppServerList[$_SERVER['HTTP_HOST']]['client_id'],
            self::scope,
            self::AppServerList[$_SERVER['HTTP_HOST']]['redirect_uri'],
            self::AppServerList[$_SERVER['HTTP_HOST']]['nonce']
        );
        return redirect($redirect_uri);  //跳转至店铺后台，店铺后台获取到参数，再次重定向到本控制器的code方法中
    }

    /**
     * code换取token
     * xshoppy重定向到第三方时，附带code参数
     * @return string
     */
    public function code()
    {
        $shop = $this->request->get('shop');
        $code = $this->request->get('code');
        $hmac = $this->request->get('hmac');
        $nonce = $this->request->get('state');
        $timestamp = $this->request->get('timestamp');

        if(strpos($shop,'http') != true){
            $shop = 'https://'.$shop;
        }

        //1 校验hmac字段
        if (empty($shop)
            || empty($code)
            || empty($hmac)
            || empty($timestamp)) {
            return "Invalid Parameter";
        }

        //2 校验 nonce
        if ($nonce != self::AppServerList[$_SERVER['HTTP_HOST']]['nonce']) {
            return "Invalid Nonce";
        }

        //3 验证hmac是有效的。HMAC由Shoplazza签名
        $client_secret = self::AppServerList[$_SERVER['HTTP_HOST']]['client_secret'];
        $query_string = sprintf('code=%s&shop=%s&timestamp=%d', $code, $shop, $timestamp);
        $myHmac = base64_encode(hash_hmac('sha256', $query_string, $client_secret));
        if ($hmac !== $myHmac) {
//            return "Invalid Hmac";
        }

        //4 验证hostname  {store_name}.xshoppy.shop
        $pattern = '/(https|http)\:\/\/[a-zA-Z0-9][a-zA-Z0-9\-]*\.myshopify\.com[\/]?/';
        if (!preg_match($pattern, 'https://' . $shop)) {
//            return "Invalid Domain";
        }

        //发送post请求 , 开始获取token
        $params = [
            'client_id' => self::AppServerList[$_SERVER['HTTP_HOST']]['client_id'],
            'client_secret' => self::AppServerList[$_SERVER['HTTP_HOST']]['client_secret'],
            'grant_type' => 'authorization_code',
            'code' => $code,
            'redirect_uri' => self::AppServerList[$_SERVER['HTTP_HOST']]['redirect_uri'],
        ];

        $result = $this->sendRequest($shop . self::GET_TOKEN_URL, $params);

        $resultStr = json_decode($result, true);
        if (isset($resultStr['code']) && $resultStr['code'] == 0) {
            echo  json_encode($resultStr,true);
            die;
            header('Location: ' . $shop . '/admin/applications/app/' . self::AppServerList[$_SERVER['HTTP_HOST']]['app_name']);
        }
        pd($resultStr);

    }

    /**
     * xshoppy嵌入的后台页面
     */
    public function admin()
    {
        //验证开始
        $shop = $this->request->get('shop');
        $code = $this->request->get('code');
        $hmac = $this->request->get('hmac');
        $timestamp = $this->request->get('timestamp');

//        pd($shop,$code,$hmac,$hmac,$timestamp);
        //1 校验hmac字段
        if (empty($shop)
            || empty($code)
            || empty($hmac)
            || empty($timestamp)) {
            return "Invalid Parameter";
        }

        $client_secret = self::AppServerList[$_SERVER['HTTP_HOST']]['client_secret'];
        $query_string = sprintf('code=%s&shop=%s&timestamp=%d', $code, $shop, $timestamp);
        $myHmac = base64_encode(hash_hmac('sha256', $query_string, $client_secret));
        if ($hmac !== $myHmac) {
            return "Invalid Hmac";
        }

        echo 'this is the management page of the ' . self::AppServerList[$_SERVER['HTTP_HOST']]['app_name'];
    }


    /**
     * 刷新token接口
     */
    public function refreshToken()
    {
        $refresh_token = $this->request->get('refresh_token');
        $shop = $this->request->get('shop');
        $params = [
            'client_id' => self::AppServerList[$_SERVER['HTTP_HOST']]['client_id'],
            'client_secret' => self::AppServerList[$_SERVER['HTTP_HOST']]['client_secret'],
            'grant_type' => 'refresh_token',
            'refresh_token' => $refresh_token,
            'redirect_uri' => self::AppServerList[$_SERVER['HTTP_HOST']]['redirect_uri'],
        ];

        $result = $this->sendRequest($shop . self::GET_TOKEN_URL, $params);
        $resultStr = json_decode($result, true);
        print_r($resultStr);
    }

    /**
     * 查询token是否有效
     */
    public function getTokenInfo()
    {
        $url = self::SHOP_DOMIN . '/test';
        $token = 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ0ZXN0X2NsaWVudF8xIiwiZXhwIjoxNjE5ODQwMDgxLCJzdWIiOiJzY290dCJ9.CjRxxH_GJv87fagxVoqgsJrwa4yYNzleXYXEj2s1EhftY9o8dkCjcCs7EGEhTTeOrmtTpvVjAAebSNsjKNA2tg';

        $result = $this->sendRequest($url, [], $token);
        echo json_encode($result);
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    public function sendRequest($url, $data)
    {
        //初使化init方法
        $ch = curl_init();
        //指定URL
        curl_setopt($ch, CURLOPT_URL, $url);
        //设定请求后返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //声明使用POST方式来进行发送
        curl_setopt($ch, CURLOPT_POST, 1);
        //发送什么数据呢
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //发送请求
        $output = curl_exec($ch);
        //关闭curl
        curl_close($ch);
        //返回数据
        return $output;
    }


}
